<template>
  <h2>当前求和为：{{ sum }}</h2>
  <button @click="sum++">点我+1</button>
  <hr />
  <h2>当前信息为：{{ msg }}</h2>
  <button @click="msg += '！'">修改信息</button>
  <hr />
  <h2>姓名：{{ person.name }}</h2>
  <h2>salary：{{ person.job.j1.salary }}k</h2>
  <button @click="person.name += '~'">修改人名</button>
  <button @click="person.job.j1.salary += 0.5">涨薪</button>
</template>

<script>
import { ref, reactive, watch } from "vue";
export default {
  name: "App",
  /* watch: {
    // sum(newValue, oldValue) {
    //   console.log("sum值变化了", newValue, oldValue);
    // },

    sum: {
      // deep: true,
      immediate: true,
      handler(newValue, oldValue) {
        console.log("sum值变化了", newValue, oldValue);
      },
    },
  }, */
  setup() {
    let sum = ref(0);
    let msg = ref("hi");
    let person = reactive({
      name: "赵四",
      job: {
        j1: {
          salary: 8,
        },
      },
    });

    // 1. 监视 ref 定义的响应式数据  1个
    /* watch(sum, (newValue, oldValue) => {
      console.log("sum值变化了", newValue, oldValue);
    }); */

    // 2. 监视 ref 定义的响应式数据  多个
    /* watch(
      [sum, msg],
      (newValues, oldValues) => {
        console.log("值变化了", newValues, oldValues);
      },
      {
        immediate: true,
      }
    ); */

    // 3. 监视 reactive 定义的响应式数据
    //    此处无法正确获取oldValue
    //    强制开启了深度监视（deep 配置无效）
    /* watch(person, (newValue, oldValue) => {
      console.log("person变化了", newValue, oldValue);
    }); */

    // 4. 监视 reactive 定义的响应式数据中的 某个属性
    watch(
      () => person.name,
      (newValue, oldValue) => {
        console.log("person.name变化了", newValue, oldValue);
      }
    );

    // 5. 监视 reactive 定义的响应式数据中的 某些属性  需要深度监视job就设置deep: true
    watch(
      [() => person.name, () => person.job],
      (newValue, oldValue) => {
        console.log("person变化了", newValue, oldValue);
      },
      { deep: true }
    );

    return {
      sum,
      msg,
      person,
    };
  },
};
</script>
